import { Button, Input, InputNumber, message, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { useEffect, useState } from 'react';
import { getEntGrade, GradeType, setEntGrade } from './data';
const EntSetGrade: React.FC<any> = () => {
  const [isSet, setIsSet] = useState<boolean>(false);
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  const [saveLoading, setLoading] = useState<boolean>(false);
  // 判断俩区间是否相交
  const judgeTwoSectionsIsIntersect = (section1: number[], section2: number[]) => {
    // 只需要判断，俩区间的最小值中的最大值 小于等于 俩区间最大值中的最小值，
    // 那么就相交
    // 俩区间的最小值中的最大值
    const maxInMins = Math.max(...[Math.min(...section1), Math.min(...section2)]);
    // 俩区间的最大值中的最小值
    const minInMaxs = Math.min(...[Math.max(...section1), Math.max(...section2)]);

    // return maxInMins < minInMaxs;
    // return maxInMins <= minInMaxs;
    return maxInMins < minInMaxs || Math.max(...section1) == Math.max(...section2);
  };
  // 判断相交整体函数
  const judgeIntersect = (newarr: number[][]) => {
    let isIntersect = false;

    a: for (let i = 0; i < newarr.length - 1; i++) {
      // 如果相交，则终止循环
      b: for (let j = i + 1; j < newarr.length; j++) {
        if (judgeTwoSectionsIsIntersect(newarr[i], newarr[j])) {
          isIntersect = true;
          // 如果相交，直接全部终止循环
          break a;
          break b;
        }
      }
    }
    return isIntersect;
  };
  const [listData, setListData] = useState<GradeType[]>([]);
  //新增
  const addRow = () => {
    const newRow = {
      sort: listData.length + 1,
      gradeName: '',
      startRatio: !listData.length ? 0 : '',
      endRatio: '',
      showName: '',
    };

    setListData((v: any) => {
      console.log([...v, newRow]);
      return [...v, newRow];
    });
  };

  //删除
  const del = (index: any) => {
    listData.splice(index, 1);
    setListData(listData.slice());
  };

  const columns: ColumnsType<any> = [
    {
      title: '等级',
      dataIndex: 'gradeName',
      key: 'gradeName',
      render(value, record, index) {
        return isSet ? (
          <Input
            placeholder="请输入"
            maxLength={10}
            value={record.gradeName}
            onChange={(e) => {
              const list = listData;
              list[index].gradeName = e.target.value;
              setListData(list.slice());
            }}
          ></Input>
        ) : (
          <span>{value}</span>
        );
      },
      width: '200px',
    },
    {
      title: '当前安全指数与最大安全指数的比值（N）',
      dataIndex: 'address',
      key: 'address',
      width: '250px',
      render(value, record, index) {
        return !isSet ? (
          <div className="flexr alc">
            <span style={{ width: '36px' }}>{record.startRatio}%</span>
            {index == 0 ? (
              <span style={{ margin: '0 10px', minWidth: '36px' }}>≤N≤</span>
            ) : (
              <span style={{ margin: '0 10px', minWidth: '36px' }}>＜N≤</span>
            )}
            <span>{record.endRatio}%</span>
          </div>
        ) : (
          <div className="flexr alc">
            <InputNumber
              min={0}
              max={100}
              precision={0}
              placeholder="请输入"
              addonAfter="%"
              disabled={!isSet || index == 0}
              defaultValue={record.startRatio}
              value={record.startRatio}
              onChange={(e) => {
                setListData((v) => {
                  v[index].startRatio = Number(e);
                  return [...v];
                });
              }}
            />
            {index == 0 ? (
              <span style={{ margin: '0 10px', minWidth: '36px' }}>≤N≤</span>
            ) : (
              <span style={{ margin: '0 10px', minWidth: '36px' }}>＜N≤</span>
            )}
            <InputNumber
              min={0}
              max={100}
              precision={0}
              placeholder="请输入"
              addonAfter="%"
              disabled={!isSet}
              defaultValue={record.endRatio}
              value={record.endRatio}
              onChange={(e) => {
                setListData((v) => {
                  v[index].endRatio = Number(e);
                  return [...v];
                });
              }}
            />
          </div>
        );
      },
    },
    // {
    //   title: '等级颜色',
    //   dataIndex: 'gradeColor',
    //   key: 'gradeColor',
    //   width: '100px',
    //   render(value, record, index) {
    //     return (
    //       <SelectGradeColor
    //         style={{ width: '100%' }}
    //         disabled={!isSet}
    //         value={record.gradeColor}
    //         onChange={(val: string | number) => {
    //           const list = listData;
    //           list[index].gradeColor = val;
    //           console.log(list.slice());
    //           setListData(list.slice());
    //           console.log(listData);
    //         }}
    //       />
    //     );
    //   },
    // },
    {
      title: '显示文字',
      dataIndex: 'showName',
      key: 'showName',
      render(value, record, index) {
        return isSet ? (
          <Input
            placeholder="请输入"
            maxLength={10}
            value={record.showName}
            onChange={(e) => {
              const list = listData;
              list[index].showName = e.target.value;
              setListData(list.slice());
            }}
          ></Input>
        ) : (
          <span>{value}</span>
        );
      },
      width: '200px',
    },
    {
      title: '等级颜色（背景）',
      dataIndex: 'gradeColorBackground',
      key: 'gradeColorBackground',
      render(value, record, index) {
        return isSet ? (
          <Input
            placeholder="请输入"
            maxLength={10}
            value={record.gradeColorBackground}
            onChange={(e) => {
              const list = listData;
              list[index].gradeColorBackground = e.target.value;
              setListData(list.slice());
            }}
          ></Input>
        ) : (
          <span>{value}</span>
        );
      },
      width: '150px',
    },
    {
      title: '等级颜色（形状）',
      dataIndex: 'gradeColorShape',
      key: 'gradeColorShape',
      render(value, record, index) {
        return isSet ? (
          <Input
            placeholder="请输入"
            maxLength={10}
            value={record.gradeColorShape}
            onChange={(e) => {
              const list = listData;
              list[index].gradeColorShape = e.target.value;
              setListData(list.slice());
            }}
          ></Input>
        ) : (
          <span>{value}</span>
        );
      },
      width: '150px',
    },
    {
      title: (
        <>
          {isSet ? (
            <Button type="text" size="small" onClick={() => addRow()}>
              <span className="safe-edu_table_operation_text">新增</span>
            </Button>
          ) : null}
        </>
      ),
      dataIndex: 'opr',
      key: 'opr',
      fixed: 'right',
      width: '80px',
      render(value, record, index) {
        return (
          <>
            {isSet && index != 0 ? (
              <Button type="text" size="small" onClick={() => del(index)}>
                <span className="safe-edu_table_operation_text">删除</span>
              </Button>
            ) : (
              ''
            )}
          </>
        );
      },
    },
  ];

  const updataList = async () => {
    setTableLoading(true);
    const { data } = await getEntGrade();
    setTableLoading(false);
    setListData(data);
  };

  useEffect(() => {
    updataList();
  }, []);

  //校验
  const verification = () => {
    let flag = true;
    if (listData.length) {
      flag = listData.every((item) => {
        if (!item.gradeName) {
          message.error('等级名称不能为空');
          return false;
        }
        if (!String(item.startRatio)) {
          message.error('请完善比值范围');
          return false;
        }
        if (!String(item.endRatio)) {
          message.error('请完善比值范围');
          return false;
        }
        if (Number(item.startRatio) > Number(item.endRatio)) {
          message.error('最大范围值不能小于最小范围值，请检查后提交');
          return false;
        }
        if (!item.showName) {
          message.error('显示文字不能为空');
          return false;
        }
        return true;
      });
      if (!flag) {
        return;
      }
    }
    if (listData.length > 1) {
      const newarr = listData.map((x) => {
        return [x.startRatio, x.endRatio];
      });
      console.log('newarr', newarr);
      const isCf = judgeIntersect(newarr);
      if (isCf) {
        message.error('比值范围有重叠，请检查后重新提交');
        return false;
      }
      const errArr = listData.findIndex((x) => {
        const reg = /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})$/;
        return !reg.test(x.gradeColorBackground) || !reg.test(x.gradeColorShape);
      });
      if (errArr > -1) {
        message.error('第' + (errArr + 1) + '行请输入正确的等级颜色');
        return false;
      }
    }
    return flag;
  };

  //保存
  const save = () => {
    if (!verification()) {
      return;
    }
    listData.map((v) => {
      v.startRatio = Number(v.startRatio);
      v.endRatio = Number(v.endRatio);
    });
    setLoading(true);
    setEntGrade(listData).then((res) => {
      setLoading(false);
      if (res.code == '200') {
        message.open({
          type: 'success',
          content: '保存成功',
        });
        updataList();

        setIsSet(false);
      }
    });
  };

  return (
    <div className="safe_boss_page_content">
      <div style={{ marginBottom: '24px' }}>
        {!isSet ? (
          <Button
            type="primary"
            onClick={() => {
              setIsSet(true);
            }}
          >
            设置
          </Button>
        ) : (
          <div className="flexr alc">
            <Button
              style={{ marginRight: '10px' }}
              onClick={() => {
                updataList();
                setIsSet(false);
              }}
            >
              取消
            </Button>

            <Button
              type="primary"
              loading={saveLoading}
              onClick={() => {
                save();
              }}
            >
              保存
            </Button>
          </div>
        )}
      </div>
      <Table
        sticky
        loading={tableLoading}
        dataSource={listData}
        columns={columns}
        pagination={false}
        scroll={{ x: '100%' }}
        rowKey="sort"
      />
    </div>
  );
};

export default EntSetGrade;
